const { staff_collection } = require('../config')
const { grid_collection } = require('../config')
const { db } = require('../config')
const { command } = require('../config')
const _ = command
const department = require('../action/department');
// 分别计算与网格、区域中点距离的平均值的偏离值
exports.main = async (event, context) => {
    var gridArr = [];
    for (item of department.grids) {
        for (grid of item) {
            gridArr.push(grid)
        }
    }
    var i = 1;
    var staffSum = 0;
    for (grid of gridArr) {
        console.log(gridArr.length, i, '开始更新网格：' + grid)
        // 2.在obd信息表中查找到该员工账号的obd，获取所有obd的经纬度；无经obd则下一个
        const gridStaff = await db.collection(staff_collection).where({ grid: grid, status: _.neq('离职'), position: "全职装维" }).field({ name: true, centersDistance: true }).limit(1000).get();
        var distanceSum = 0, staffArr = [];
        for (staff of gridStaff.data) {
            if (staff && staff.hasOwnProperty('centersDistance')) {
                let item = { _id: staff._id, centersDistance: staff.centersDistance, name: staff.name };
                staffArr.push(item);
                distanceSum = distanceSum + staff.centersDistance;
            }
        }
        staffSum += staffArr.length;
        var gridStaffCount = gridStaff.data.length;
        var gridDistanceAve = (distanceSum / staffSum).toFixed(2);
        console.log('装维离网格中心平均距离:', distanceSum, '/', staffSum, '=', gridDistanceAve);
        for (item of staffArr) {
            gridOffset = (item.centersDistance - gridDistanceAve).toFixed(2);
            res = await db.collection(staff_collection).doc(item._id).update({
                gridOffset: gridOffset
            });
            console.log(i, '装维', item.name, '与网格平均距离偏离值:', item.centersDistance, '-', gridDistanceAve, '=', gridOffset,res);
            i++;
        }
    }
    return '处理结束' + staffSum;
}